package yja.gzw.app.activity

import AuthResult
import PayResult
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.os.Message
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.widget.Button
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.alipay.sdk.app.PayTask
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.bottomsheet.BottomSheetDialog
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import yja.gzw.app.R
import yja.gzw.app.base.BaseActivity
import yja.gzw.app.databinding.ActivityFabusiBinding
import yja.gzw.app.model.UserData
import yja.gzw.app.viewmodel.Mainviewmodel
import java.io.File


class FabusiActivity :BaseActivity<Mainviewmodel, ActivityFabusiBinding>(R.layout.activity_fabusi){
    private lateinit var bottomSheetDialog: BottomSheetDialog
    var lists= mutableListOf<String>()
    val SDK_PAY_FLAG: Int = 1
    var scfs=0
    val SDK_AUTH_FLAG: Int = 2
    var shuzi=1
    var file: File?=null
    var pingtai=""


    override fun onResume() {
        super.onResume()

        binding.weizhixingxi.setText(UserData.diming)

    }
    private fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, GALLERY_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            data?.data?.let { uri ->
                file = File(getRealPathFromURI(uri))

                val requestFile = file?.asRequestBody("multipart/form-data".toMediaTypeOrNull())
                val body = MultipartBody.Part.createFormData("file", file?.name,requestFile!!)
                viewmodel.onluying(body)
            }
        }
    }

    private fun getRealPathFromURI(contentUri: Uri): String {
        val projection = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = contentResolver.query(contentUri, projection, null, null, null)
        val column_index = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        cursor?.moveToFirst()
        val result = cursor?.getString(column_index!!)
        cursor?.close()
        return result!!
    }
    companion object {
        private const val GALLERY_REQUEST_CODE = 1001
    }



    override fun initView() {

        binding.shipingsucai.setOnClickListener {
            openGallery()


        }

        binding.fabupingtai.setOnClickListener {
            pingtai=""
            lists.clear()
            bottomSheetDialog = BottomSheetDialog(this)
            val view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_pingtia, null)
            bottomSheetDialog.setContentView(view)
            val xuan1 =view.findViewById<CheckBox>(R.id.xuan1)
            val xuan2 =view.findViewById<CheckBox>(R.id.xuan2)
            val xuan3 =view.findViewById<CheckBox>(R.id.xuan3)
            val xuan4 =view.findViewById<CheckBox>(R.id.xuan4)

            val queding =view.findViewById<TextView>(R.id.queding)
            val quxiao =view.findViewById<TextView>(R.id.quxiao)
            val chacha =view.findViewById<ImageView>(R.id.chacha)

            chacha.setOnClickListener {
                bottomSheetDialog.dismiss()

            }
            quxiao.setOnClickListener {
                bottomSheetDialog.dismiss()
            }
            queding.setOnClickListener {


                if(xuan1.isChecked){
                    // binding.pingtai.text="抖音"
                    // pingtai += "抖音"
                    lists.add("抖音")

                }
                if(xuan2.isChecked){
                    //binding.pingtai.text="快手"
                    // pingtai += "快手"
                    lists.add("快手")

                }
                if(xuan3.isChecked){
                    //binding.pingtai.text="西瓜视频"
                    //pingtai += "西瓜视频"
                    lists.add("西瓜视频")

                }
                if(xuan4.isChecked){
                    // pingtai += "bilibili"
                    // binding.pingtai.text="bilibili"
                    lists.add("bilibili")
                }

                for ((index, list) in lists.withIndex()) {
                    if(index==lists.size-1){
                        pingtai= "$pingtai$list"
                    }else{
                        pingtai= "$pingtai$list,"

                    }


                }
                binding.pingtai.text=pingtai

                bottomSheetDialog.dismiss()
                binding.pingtai.text.toString()
            }


            bottomSheetDialog.show()


        }



        binding.aishipinggzt.setOnClickListener {
            val inten=Intent(this@FabusiActivity, AishipinggztActivity::class.java)
            inten.putExtra("leixing","4")
            inten.putExtra("moshi",scfs.toString())
            startActivity(inten)
        }
        binding.shipingmoshi.setOnClickListener {
            bottomSheetDialog = BottomSheetDialog(this)
            val view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_moshi, null)
            bottomSheetDialog.setContentView(view)
            val okButton2 =view.findViewById<TextView>(R.id.queding)
            val chahao =view.findViewById<ImageView>(R.id.chacha)
            val quxiao =view.findViewById<TextView>(R.id.quxiao)
            val xuan1 =view.findViewById<RadioButton>(R.id.xuan1)
            val xuan2 =view.findViewById<RadioButton>(R.id.xuan2)
            val xuan3 =view.findViewById<RadioButton>(R.id.xuan3)


            okButton2.setOnClickListener {



                if(xuan1.isChecked){
                    scfs=1
                    binding.scfs.text="自己使用AI生成视频"
                    binding.aishipinggzt.isVisible=true
                    binding.aishipinggzt.text = "AI视频工作台"
                    binding.bushiyongai.isVisible=false
                } else if(xuan2.isChecked){
                    scfs=2
                    binding.scfs.text="第二方使用AI生成视频"
                    binding.bushiyongai.isVisible=false
                    binding.aishipinggzt.isVisible=true
                    binding.aishipinggzt.text = "填写AI生成视频素材"

                }else{
                    scfs=3
                    binding.scfs.text="自己使用AI生成视频"
                    binding.aishipinggzt.isVisible=false
                    binding.bushiyongai.isVisible=true
                }

                bottomSheetDialog.dismiss()


            }
            chahao.setOnClickListener {
                bottomSheetDialog.dismiss()
            }
            quxiao.setOnClickListener {

                bottomSheetDialog.dismiss()
            }

            bottomSheetDialog.show()



        }

        binding.dinwei.setOnClickListener {
            val inten= Intent(this@FabusiActivity, MapsActivity::class.java)
            startActivity(inten)

        }

        binding.jian.setOnClickListener {
            shuzi--
            binding.shuzi.text=shuzi.toString()


        }
        binding.jia.setOnClickListener {
            shuzi++
            binding.shuzi.text=shuzi.toString()

        }



        binding.fabuanniu.setOnClickListener {
            val biaoti=binding.biaotizhan.text.toString()
            val pintia=binding.pingtai.text.toString()
            val biaotinr=binding.biaotinr.text.toString()
            val shipinneirun=binding.shipingneirun.text.toString()
            val xuqiubiaoti=binding.xuqiubiaoti.text.toString()

            if(UserData.wengbengsucai==""){

                UserData.wengbengsucai=binding.shurukuangneirung.text.toString()
            }



            viewmodel.onchuanjiandingdanwang(UserData.token, mapOf("platform_id" to pintia
                ,"title" to biaotinr,"type" to "2","release_type" to scfs.toString(),"release_num" to shuzi.toString(),
                "address" to UserData.diming,"label" to biaoti,"video_url" to UserData.hechengdeshipinglianjie,
                "content" to shipinneirun,"material" to UserData.tupiansecai,"text_material" to UserData.wengbengsucai
                ,"need_title" to xuqiubiaoti,"layout" to UserData.pingmufangxiang.toString(),"tts_per" to "4100"
            ))
        }


    }

    override fun dataObservese() {


        viewmodel.onlusc.observe(this, Observer {
            if(it.code==1){

                val shipinglujin= "http://117ai.32.hzgqapp.com"+it.data.url

                UserData.hechengdeshipinglianjie=shipinglujin
                Log.e("视频上传的路径", shipinglujin)

                Glide.with(this)
                    .setDefaultRequestOptions(
                        RequestOptions()
                            .frame(0)
                            .centerCrop()
                    )
                    .load(shipinglujin)
                    .into(binding.shipingsucai)

            }


        })


        viewmodel.onZhifushow.observe(this, Observer {
            if(it.code==1){
                // finish()
                // bottomSheetDialog.dismiss()
                //todo 调起支付弹窗
                UserData.wengbengsucai=""
                zhifujieu(it.data.toString())




            }else{
                Toast.makeText(this, it.msg, Toast.LENGTH_SHORT).show()

            }

        })

        //todo 支付弹窗
        viewmodel.onchuanjiandingdan.observe(this, Observer {
            if(it.code==1){
                val id=it.data.id
                bottomSheetDialog = BottomSheetDialog(this)
                val view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_layout, null)
                bottomSheetDialog.setContentView(view)


                val okButton =view.findViewById<Button>(R.id.okButton)
                val xuan1 =view.findViewById<RadioButton>(R.id.xuan1)
                val titless =view.findViewById<TextView>(R.id.title)

                titless.text="￥${4*shuzi}.00"

                okButton.setOnClickListener {
                    var zhifu="wechat"

                    //todo 爆红不管
                    if(xuan1.isChecked){
                        zhifu="wechat"

                    }else{
                        zhifu="alipay"
                    }

                    viewmodel.onZhifushowwang(UserData.token, mapOf("order_id" to id,"type" to "four","pay_type" to zhifu,"method" to "app"))





                }

                bottomSheetDialog.show()



            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()

            }

        })

    }

    fun zhifujieu(info: String) {
        val orderInfo = info // 订单信息
        val payRunnable = Runnable {
            val alipay = PayTask(this)
            val result = alipay.payV2(orderInfo, true)
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }

        val payThread = Thread(payRunnable)
        payThread.start()
    }

    @SuppressLint("HandlerLeak")
    var mHandler: Handler = object : Handler() {
        @Suppress("unused")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    Log.e("支付步骤","1")
                    val payResult: PayResult = PayResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo: String = payResult.getResult() // 同步返回需要验证的信息
                    val resultStatus: String = payResult.getResultStatus()
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Log.e("支付步骤","2")
                        //todo 支付成功
                        Toast.makeText(this@FabusiActivity, "支付成功", Toast.LENGTH_SHORT).show()
                        finish()
                        bottomSheetDialog.dismiss()




                    } else {
                        //todo 放弃支付
                        Log.e("支付步骤","3")
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(this@FabusiActivity, "支付失败", Toast.LENGTH_SHORT).show()
                    }
                }

                SDK_AUTH_FLAG -> {
                    Log.e("支付步骤","4")
                    val authResult: AuthResult = AuthResult(msg.obj as Map<String?, String?>, true)
                    val resultStatus: String = authResult.getResultStatus()

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(
                            resultStatus,
                            "9000"
                        ) && TextUtils.equals(authResult.getResultCode(), "200")
                    ) {
                        Log.e("支付步骤","5")
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(this@FabusiActivity, "支付成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Log.e("支付步骤","6")
                        // 其他状态值则为授权失败
                        Toast.makeText(this@FabusiActivity, "支付失败", Toast.LENGTH_SHORT).show()
                    }
                }

                else -> { Log.e("支付步骤","7")}
            }
        }
    }




}